package net.wofly.right.shiro;

import net.wofly.common.json.XiNiaoJSON;
import net.wofly.common.util.ReturnBean;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.PrintWriter;

/**
 * Desc:
 * Created by LiuJianbo on 2017/11/8.
 */
public class MyAuthcFilter extends FormAuthenticationFilter {

    private static final Logger log = LoggerFactory.getLogger(MyAuthcFilter.class);

    /**
     * 所有请求都会经过的方法。
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        if (isLoginRequest(request, response)) {
            if (isLoginSubmission(request, response)) {
                return executeLogin(request, response);
            } else {
                return true;
            }
        } else {
            log.info(">>>用户未登录，不能访问相关资源");
            response.setCharacterEncoding("UTF-8");
            PrintWriter out = response.getWriter();
            ReturnBean returnBean = new ReturnBean(-999, "请登录");
            out.println(XiNiaoJSON.toJSONString(returnBean));
            out.flush();
            out.close();
            return false;
        }
    }
}
